package com.example.mall.order.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@EnableRabbit
@Configuration
public class RabbitConfig {

    private static final String EVENT_EXCHANGE = "event.exchange";

    private static final String MAIN_QUEUE = "main.queue";

    private static final String DELAY_QUEUE = "delay.queue";

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 交换机
     *
     * @return 交换机
     */
    @Bean
    public Exchange eventExchange() {
        return new TopicExchange(EVENT_EXCHANGE);
    }

    /**
     * 延时队列
     * 延时队列原理：publisher -> event.exchange -> delay.queue -> event.exchange -> main.queue
     * publisher -> event.exchange：routing-key 为 delay.queue
     * delay.queue -> event.exchange：delay.queue延时队列，设置过期时间，时间一到则转发到event.exchange
     * event.exchange -> main.queue：delay.queue发到event.exchange中的routing-key为main.queue
     *
     * @return 延时队列
     */
    @Bean
    public Queue delayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", EVENT_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", MAIN_QUEUE);
        arguments.put("x-message-ttl", 20000);
        return new Queue(DELAY_QUEUE, true, false, false, arguments);
    }

    /**
     * 普通队列
     *
     * @return 普通队列
     */
    @Bean
    public Queue mainQueue() {
        return new Queue(MAIN_QUEUE);
    }

    /**
     * 延时队列与交换机的绑定
     *
     * @return 延时队列与交换机的绑定
     */
    @Bean
    public Binding delayQueueBinding() {
        return new Binding(DELAY_QUEUE, Binding.DestinationType.QUEUE, EVENT_EXCHANGE, DELAY_QUEUE, null);
    }

    /**
     * 普通队列与交换机的绑定
     *
     * @return 普通队列与交换机的绑定
     */
    @Bean
    public Binding mainQueueBinding() {
        return new Binding(MAIN_QUEUE, Binding.DestinationType.QUEUE, EVENT_EXCHANGE, MAIN_QUEUE, null);
    }
}
